<template>
    <div>
                <!-- 头部 -->
        <van-nav-bar @click-left="$router.push('/index')" left-arrow>
            <template #title>
                <van-search shape="round" v-model="keyword" placeholder="请输入搜索关键词" />
            </template>
            <template #right>
                <span @click="searchFn">搜索</span>
            </template>
        </van-nav-bar>
        <div class="content">
            <h1>历史记录</h1>
            <ul>
                <li v-for="(item,index) in histroy" :key="index" @click="histroySearch(item)">{{item}}</li>
            </ul>
        </div>
        <hr>
        <div class="content">
            <h1>搜索结果</h1>
            <ul>
                <li v-for="item in result" :key="item.id" 
                v-html="item.title.replaceAll(keyword,`<span style='color:red'>${keyword}</span>`)"
                @click="toDetail(item.id)"></li>
            </ul>
        </div>
    </div>
</template>

<script>
import {search} from "@/api/article.js"
export default {
    data(){
        return {
            keyword: "",
            result: [],
            histroy: JSON.parse(localStorage.getItem("history")) || []
        }
    },
    methods: {
        searchFn(){
            // 判断历史记录中 关键词是否存在其中，如果不存在则添加进数组中
            if(this.histroy.indexOf(this.keyword) == -1){
                this.histroy.push(this.keyword)
                localStorage.setItem("history",JSON.stringify(this.histroy))
            }

            search({
                keyword: this.keyword
            }).then(res=>{
                console.log(res);
                this.result = res.data.data;
            })
        },
        // 跳转到文章详情
        toDetail(id){
            this.$router.push({
                path: "/articleDetail",
                query: {
                    id
                }
            })
        },
        histroySearch(val){
            this.keyword = val;
            this.searchFn()
        }
    }
}
</script>

<style lang="less" scoped>
/deep/.van-nav-bar__title{
    max-width: inherit;
    width: 70%;
    .van-icon-search{
        color: #000;
    }
}
/deep/.van-icon-arrow-left{
    color: #000;
}
.content{
    margin-top: 20px;
    padding: 0 5px;
    h1{
        font-size: 18px;
        font-weight: bold;
        margin: 20px 0;
    }
    ul{
        li{
            font-size: 14px;
            padding: 5px 0;
        }
    }
}
</style>